<template>
  <nut-popup 
    v-model:visible="visible" 
    position="bottom" 
    :style="{ height: '80%' }"
    round
    closeable
    @close="handleClose"
  >
    <view class="map-picker-container">
      <!-- 头部 -->
      <view class="flex justify-between items-center p-[30rpx] border-b border-gray-200">
        <text class="text-[32rpx] font-bold text-gray-800">选择任务地点</text>
        <nut-button 
          type="primary" 
          size="small"
          @click="confirmLocation"
        >
          确认位置
        </nut-button>
      </view>

      <!-- 搜索框 -->
      <view class="p-[30rpx] border-b border-gray-200">
        <view class="flex items-center bg-gray-100 rounded-[20rpx] p-[20rpx]">
          <IconFont name="search" class="text-[32rpx] text-gray-500 mr-[20rpx]" />
          <input
            v-model="searchKeyword"
            type="text"
            class="flex-1 text-[28rpx] bg-transparent"
            placeholder="搜索地点或输入详细地址，回车键解析地址"
            @keyup.enter="handleSearch"
          />
          <nut-button 
            size="small"
            type="primary"
            class="ml-[20rpx]"
            @click="handleSearch"
          >
            解析
          </nut-button>
        </view>
      </view>
    </view>
  
  </nut-popup>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick, computed } from 'vue'
import Taro from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro'
import { geocodeAddress } from '@/utils/geocoder'
import { isApiKeyConfigured } from '@/utils/mapConfig'

/**
 * 地图选择器组件 (H5兼容版本)
 * @description 为H5环境提供地址选择功能，支持快速选择、自定义地址和线上任务
 */

// 定义接口
interface LocationInfo {
  name: string
  address: string
  latitude: number
  longitude: number
}

interface QuickLocation {
  name: string
  address: string
  latitude: number
  longitude: number
}

// Props
interface Props {
  modelValue: boolean
  defaultLocation?: {
    latitude: number
    longitude: number
    address?: string
  }
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  defaultLocation: () => ({
    latitude: 39.9042,
    longitude: 116.4074,
    address: '北京市'
  })
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [location: LocationInfo]
}>()

// 响应式数据
const visible = ref(false)
const searchKeyword = ref('')
const selectedQuickIndex = ref(-1)
const isOnlineTask = ref(false)

// 自定义地址相关
const selectedProvince = ref('')
const selectedCity = ref('')
const customAddress = ref('')
const customLongitude = ref('')
const customLatitude = ref('')

// 选择器相关
const showProvincePicker = ref(false)
const showCityPicker = ref(false)
const provinceValue = ref<string[]>([])
const cityValue = ref<string[]>([])

// 快速选择地址
const quickLocations = ref<QuickLocation[]>([
  { name: '北京市朝阳区', address: '北京市朝阳区建国门外大街1号', latitude: 39.9042, longitude: 116.4074 },
  { name: '上海市浦东新区', address: '上海市浦东新区陆家嘴环路1000号', latitude: 31.2304, longitude: 121.4737 },
  { name: '广州市天河区', address: '广州市天河区珠江新城花城大道85号', latitude: 23.1291, longitude: 113.2644 },
  { name: '深圳市南山区', address: '深圳市南山区科技园南区深圳湾科技生态园', latitude: 22.5431, longitude: 113.9344 }
])

// 省份选项
const provinceOptions = ref([
  { text: '北京市', value: '北京市' },
  { text: '上海市', value: '上海市' },
  { text: '广东省', value: '广东省' },
  { text: '江苏省', value: '江苏省' },
  { text: '浙江省', value: '浙江省' },
  { text: '山东省', value: '山东省' },
  { text: '河南省', value: '河南省' },
  { text: '四川省', value: '四川省' },
  { text: '湖北省', value: '湖北省' },
  { text: '湖南省', value: '湖南省' }
])

// 城市选项
const cityOptions = ref([
  { text: '北京市', value: '北京市' },
  { text: '上海市', value: '上海市' },
  { text: '广州市', value: '广州市' },
  { text: '深圳市', value: '深圳市' },
  { text: '南京市', value: '南京市' },
  { text: '杭州市', value: '杭州市' },
  { text: '济南市', value: '济南市' },
  { text: '郑州市', value: '郑州市' },
  { text: '成都市', value: '成都市' },
  { text: '武汉市', value: '武汉市' }
])

// 计算显示的地址信息
const displayAddress = computed(() => {
  if (isOnlineTask.value) {
    return {
      name: '线上任务',
      address: '无需指定具体地点，可远程完成',
      latitude: 0,
      longitude: 0
    }
  }
  
  if (selectedQuickIndex.value >= 0) {
    return quickLocations.value[selectedQuickIndex.value]
  }
  
  if (selectedProvince.value && selectedCity.value) {
    const address = `${selectedProvince.value}${selectedCity.value}${customAddress.value}`
    return {
      name: `${selectedProvince.value}${selectedCity.value}`,
      address: address,
      latitude: parseFloat(customLatitude.value) || 0,
      longitude: parseFloat(customLongitude.value) || 0
    }
  }
  
  return {
    name: '未知地点',
    address: '请选择或输入地址',
    latitude: 0,
    longitude: 0
  }
})

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    nextTick(() => {
      initLocation()
    })
  }
})

// 监听 visible 变化
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

/**
 * 初始化位置信息
 */
const initLocation = () => {
  // 重置选择状态
  selectedQuickIndex.value = -1
  isOnlineTask.value = false
  selectedProvince.value = ''
  selectedCity.value = ''
  customAddress.value = ''
  customLongitude.value = ''
  customLatitude.value = ''
  
  // 如果有默认位置，尝试匹配快速选择
  if (props.defaultLocation.address) {
    const matchedIndex = quickLocations.value.findIndex(location => 
      location.address.includes(props.defaultLocation.address || '')
    )
    if (matchedIndex >= 0) {
      selectedQuickIndex.value = matchedIndex
    }
  }
}

/**
 * 选择快速位置
 */
const selectQuickLocation = (index: number) => {
  selectedQuickIndex.value = index
  isOnlineTask.value = false
  // 清空自定义地址
  selectedProvince.value = ''
  selectedCity.value = ''
  customAddress.value = ''
  customLongitude.value = ''
  customLatitude.value = ''
}

/**
 * 选择线上任务
 */
const selectOnlineTask = () => {
  isOnlineTask.value = true
  selectedQuickIndex.value = -1
  // 清空自定义地址
  selectedProvince.value = ''
  selectedCity.value = ''
  customAddress.value = ''
  customLongitude.value = ''
  customLatitude.value = ''
}



/**
 * 处理搜索
 */
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) return
  
  // 首先在快速选择中搜索
  const matchedIndex = quickLocations.value.findIndex(location => 
    location.name.includes(searchKeyword.value) || 
    location.address.includes(searchKeyword.value)
  )
  
  if (matchedIndex >= 0) {
    selectQuickLocation(matchedIndex)
    Taro.showToast({
      title: '找到匹配地址',
      icon: 'success'
    })
    return
  }
  
  // 如果快速选择中没有找到，尝试使用腾讯地图API解析地址
  try {
    Taro.showLoading({ title: '正在解析地址...' })
    
    const result = await geocodeAddress(searchKeyword.value)
    
    // 更新自定义地址信息
    selectedProvince.value = result.name.substring(0, 2) || ''
    selectedCity.value = result.name.substring(2) || ''
    customAddress.value = result.address.replace(result.name, '') || ''
    customLatitude.value = result.latitude.toString()
    customLongitude.value = result.longitude.toString()
    
    // 清空快速选择
    selectedQuickIndex.value = -1
    isOnlineTask.value = false
    
    Taro.hideLoading()
    Taro.showToast({
      title: '地址解析成功',
      icon: 'success'
    })
  } catch (error) {
    Taro.hideLoading()
    Taro.showToast({
      title: '地址解析失败，请手动选择',
      icon: 'none'
    })
  }
}

/**
 * 省份确认
 */
const onProvinceConfirm = (val: any) => {
  showProvincePicker.value = false
  if (val.selectedValue && val.selectedValue.length > 0) {
    selectedProvince.value = val.selectedValue[0]
    // 清空城市选择
    selectedCity.value = ''
  }
}

/**
 * 城市确认
 */
const onCityConfirm = (val: any) => {
  showCityPicker.value = false
  if (val.selectedValue && val.selectedValue.length > 0) {
    selectedCity.value = val.selectedValue[0]
  }
}

/**
 * 确认位置
 */
const confirmLocation = () => {
  if (isOnlineTask.value) {
    emit('confirm', {
      name: '线上任务',
      address: '线上任务',
      latitude: 0,
      longitude: 0
    })
    visible.value = false
    return
  }
  
  if (selectedQuickIndex.value >= 0) {
    const location = quickLocations.value[selectedQuickIndex.value]
    emit('confirm', { ...location })
    visible.value = false
    return
  }
  
  if (selectedProvince.value && selectedCity.value) {
    const address = `${selectedProvince.value}${selectedCity.value}${customAddress.value}`
    emit('confirm', {
      name: `${selectedProvince.value}${selectedCity.value}`,
      address: address,
      latitude: parseFloat(customLatitude.value) || 0,
      longitude: parseFloat(customLongitude.value) || 0
    })
    visible.value = false
    return
  }
  
  Taro.showToast({
    title: '请选择或输入地址',
    icon: 'none'
  })
}

/**
 * 关闭弹窗
 */
const handleClose = () => {
  visible.value = false
}

// 暴露方法
defineExpose({
  setLocation: (location: LocationInfo) => {
    // 尝试匹配快速选择
    const matchedIndex = quickLocations.value.findIndex(l => 
      l.address === location.address
    )
    if (matchedIndex >= 0) {
      selectedQuickIndex.value = matchedIndex
    } else {
      // 设置为自定义地址
      selectedProvince.value = location.name.substring(0, 2)
      selectedCity.value = location.name.substring(2)
      customAddress.value = location.address.replace(location.name, '')
      customLatitude.value = location.latitude.toString()
      customLongitude.value = location.longitude.toString()
    }
  }
})
</script>

<style lang="scss">
.map-picker-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .flex-1 {
    flex: 1;
  }
}
</style> 